package cn.kgc.springcloud.controller;

import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.service.ClazzService;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author: mosin
 * @version: v1.0  2022/6/15
 */
@RestController
@RequestMapping("clazzs")
public class ClazzController {

    @Autowired
    private ClazzService clazzService;

    @GetMapping
    public List<Clazz> getClazzs(){
        List<Clazz> all = clazzService.getAll();
        return all;
    }

    @PostMapping
    public Clazz addClazz(String name, Integer tagId, MultipartFile logo){

        String originalFilename = logo.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String finalName = uuid+"."+ StringUtils.getFilenameExtension(originalFilename);
        //文件上传
        try {
            logo.transferTo(new File("D:\\upload", finalName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将数据存入数据库  clazz
        Clazz  clazz = Clazz.builder().name(name).path("/" + finalName).tagId(tagId).build();
        return clazzService.addClazz(clazz);
    }


    @DeleteMapping("{id}")
    public void deleteClazz(@PathVariable("id") Integer id){
        clazzService.deleteClazz(id);
    }


    @GetMapping("{id}")
    public Clazz getById(@PathVariable("id") Integer id){

        return  clazzService.getById(id);
    }

}
